package api

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"go-caipu/pkg/api/helper"
	"log"
	"net/http"
	"os"
	"path"
	"path/filepath"
)

type FileResponse struct {
	Size     int64  `json:"size"`
	Path     string `json:"path"`
	FullPath string `json:"full_path"`
	Name     string `json:"name"`
	Type     string `json:"type"`
}

func (hs *HTTPServer) UploadFile(c *gin.Context) {
	var done bool
	var fileResponse FileResponse
	urlPrefix := fmt.Sprintf("%s://%s/", "http", c.Request.Host)
	fileResponse, done = hs.singleFile(c, fileResponse, urlPrefix)
	if done {
		helper.SuccessWithData(c, fileResponse)
		return
	}
	helper.SuccessWithData(c, fileResponse)
}

func (hs *HTTPServer) singleFile(c *gin.Context, fileResponse FileResponse, urlPerfix string) (FileResponse, bool) {
	files, err := c.FormFile("file")
	if err != nil {
		hs.log.Error("图片不能为空")
		return FileResponse{}, true
	}
	// 上传文件至指定目录
	guid := uuid.New().String()
	fileName := guid + GetExt(files.Filename)

	err = IsNotExistMkDir("/static/uploadfile/")
	if err != nil {
		hs.log.Error("初始化文件路径失败")
	}
	singleFile := "/static/uploadfile/" + fileName
	_ = c.SaveUploadedFile(files, singleFile)
	fileType, _ := GetType(singleFile)
	fileResponse = FileResponse{
		Size:     GetFileSize(singleFile),
		Path:     singleFile,
		FullPath: urlPerfix + singleFile,
		Name:     files.Filename,
		Type:     fileType,
	}
	//source, _ := c.GetPostForm("source")
	//err = thirdUpload(source, fileName, singleFile)
	//if err != nil {
	//	e.Error(200, errors.New(""), "上传第三方失败")
	//	return FileResponse{}, true
	//}
	fileResponse.Path = "/static/uploadfile/" + fileName
	fileResponse.FullPath = "/static/uploadfile/" + fileName
	return fileResponse, false
}

// GetExt 获取文件后缀
func GetExt(fileName string) string {
	return path.Ext(fileName)
}

// IsNotExistMkDir 检查文件夹是否存在
// 如果不存在则新建文件夹
func IsNotExistMkDir(src string) error {
	if exist := !CheckExist(src); exist == false {
		if err := MkDir(src); err != nil {
			return err
		}
	}

	return nil
}

// CheckExist 检查文件是否存在
func CheckExist(src string) bool {
	_, err := os.Stat(src)

	return os.IsNotExist(err)
}

// MkDir 新建文件夹
func MkDir(src string) error {
	err := os.MkdirAll(src, os.ModePerm)
	if err != nil {
		return err
	}

	return nil
}

// GetFileSize 获取文件大小
func GetFileSize(filename string) int64 {
	var result int64
	err := filepath.Walk(filename, func(path string, f os.FileInfo, err error) error {
		result = f.Size()
		return nil
	})
	if err != nil {
		log.Println(err)
		return 0
	}
	return result
}

// GetType 获取文件类型
func GetType(p string) (string, error) {
	file, err := os.Open(p)
	defer file.Close()
	if err != nil {
		log.Println(err)
		os.Exit(1)
	}

	buff := make([]byte, 512)

	_, err = file.Read(buff)

	if err != nil {
		log.Println(err)
	}

	filetype := http.DetectContentType(buff)

	//ext := GetExt(p)
	//var list = strings.Split(filetype, "/")
	//filetype = list[0] + "/" + ext
	return filetype, nil
}
